package com.huike.report.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.dto.TbClueDTO;
import com.huike.clues.domain.entity.SysDept;
import com.huike.clues.mapper.DeptMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.common.exception.BaseException;
import com.huike.common.utils.DateUtils;
import com.huike.common.utils.SecurityUtils;
import com.huike.report.domain.vo.IndexBaseInfoVO;
import com.huike.report.domain.vo.IndexTodayInfoVO;
import com.huike.report.domain.vo.IndexTodoInfoVO;
import com.huike.report.mapper.IndexMapper;
import com.huike.report.result.ReportIndexStatisticsData;
import com.huike.report.service.IndexService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description IReportServiceImpl
 * @Author chenjialiang
 * @Date 2023-10-16
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class IndexServiceImpl implements IndexService {

    // @Autowired
    private final IndexMapper indexMapper;

    private final TbAssignRecordMapper tbAssignRecordMapper;

    private final DeptMapper deptMapper;

    /**
     * 基础数据查询
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexBaseInfoVO getBaseInfo(String beginCreateTime, String endCreateTime) {
        IndexBaseInfoVO result = new IndexBaseInfoVO();
        String username = SecurityUtils.getUsername();

        result.setCluesNum(indexMapper.getCluesNum(beginCreateTime, endCreateTime, username));
        result.setBusinessNum(indexMapper.getBusinessNum(beginCreateTime, endCreateTime, username));
        result.setContractNum(indexMapper.getContractNum(beginCreateTime, endCreateTime, username));
        result.setSalesAmount(indexMapper.getSalesAmount(beginCreateTime, endCreateTime, username));

        return result;
    }

    /**
     * 获取今日数据简报
     *
     * @return
     */
    @Override
    public IndexTodayInfoVO getTodayInfo() {

        IndexTodayInfoVO result = new IndexTodayInfoVO();
        String username = SecurityUtils.getUsername();

        String todayTime = DateUtils.getDate();

        result.setTodayCluesNum(indexMapper.getTodayCluesNum(todayTime, username));
        result.setTodayBusinessNum(indexMapper.getTodayBusinessNum(todayTime, username));
        result.setTodayContractNum(indexMapper.getTodayContractNum(todayTime, username));
        result.setTodaySalesAmount(indexMapper.getTodaySalesAmount(todayTime, username));

        return result;
    }

    /**
     * 代办数据
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexTodoInfoVO getTodoInfo(String beginCreateTime, String endCreateTime) {
        IndexTodoInfoVO result = new IndexTodoInfoVO();
        String username = SecurityUtils.getUsername();

        // 待跟进
        result.setTofollowedCluesNum(indexMapper.getTofollowedCluesNum(beginCreateTime, endCreateTime, username));
        // 待分配
        result.setToallocatedCluesNum(indexMapper.getToallocatedCluesNum(beginCreateTime, endCreateTime, username));

        result.setTofollowedBusinessNum(indexMapper.getTofollowedBusinessNum(beginCreateTime, endCreateTime, username));

        result.setToallocatedBusinessNum(indexMapper.getToallocatedBusinessNum(beginCreateTime, endCreateTime,
                username));

        return result;
    }

    /**
     * 商机龙虎榜
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<ReportIndexStatisticsData> businessChangeStatistics(String beginCreateTime, String endCreateTime) {
        List<ReportIndexStatisticsData> result = indexMapper.getBusinessChangeStatistics(beginCreateTime,
                endCreateTime);
        log.info("商机龙虎榜返回数据：{}", result);
        Integer sum = indexMapper.getBusinessCount(beginCreateTime, endCreateTime);
        // 利用Lambda表达式中的管道流中的map方法将排行榜数据进行进一步封装：转化率
        result.stream().map(item -> {
            // String createBy = item.getCreateBy();
            // String createBy = item.getCreate_by();
            // Integer sum = indexMapper.getCountByOne(beginCreateTime, endCreateTime,createBy);
            item.setRadio(getRadio(sum, item.getNum()));
            return item;
        }).collect(Collectors.toList());
        return result;
    }

    /**
     * 转换率
     *
     * @param all
     * @param num
     * @return
     */
    private BigDecimal getRadio(Integer all, Integer num) {
        if (all.intValue() == 0) {
            return new BigDecimal(0);
        }
        BigDecimal numBigDecimal = new BigDecimal(num);
        BigDecimal allBigDecimal = new BigDecimal(all);
        BigDecimal divide = numBigDecimal.divide(allBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
        return divide.multiply(new BigDecimal(100));
    }



    /*    *//**
     * 线索龙虎榜
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     *//*
    @Override
    public List<ReportIndexStatisticsData> salesStatistic(String beginCreateTime, String endCreateTime) {

        List<ReportIndexStatisticsData> result = indexMapper.getSalesStatistic(beginCreateTime,endCreateTime);

        return null;
    }*/


    /**
     * 线索转化龙虎榜
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<ReportIndexStatisticsData> salesStatistic(LocalDate beginCreateTime, LocalDate endCreateTime) {

        LocalDateTime beginMinTime = LocalDateTime.of(beginCreateTime, LocalTime.MIN);
        LocalDateTime endMaxTime = LocalDateTime.of(endCreateTime, LocalTime.MAX);

        QueryWrapper<TbClue> tbClueQueryWrapper = new QueryWrapper<>();
        tbClueQueryWrapper.between("create_time", beginMinTime, endMaxTime);
        tbClueQueryWrapper.groupBy("create_by").select("create_by");
        List<TbClue> tbClues = indexMapper.selectList(tbClueQueryWrapper);

        List<ReportIndexStatisticsData> reportIndexStatisticsDataList = new ArrayList<>();
        for (TbClue tbClue : tbClues) {

            ReportIndexStatisticsData reportIndexStatisticsData = new ReportIndexStatisticsData();

            reportIndexStatisticsData.setCreateBy(tbClue.getCreateBy());

            // 总数
            QueryWrapper<TbClue> tbClueQueryWrapper1 = new QueryWrapper<>();
            tbClueQueryWrapper1.between("create_time", beginMinTime, endMaxTime);
            tbClueQueryWrapper1.eq("create_by", tbClue.getCreateBy());
            Integer num = indexMapper.selectCount(tbClueQueryWrapper1);

            if (num != null) {
                reportIndexStatisticsData.setNum(num);
            }

            // 转化数
            QueryWrapper<TbClue> tbClueQueryWrapper2 = new QueryWrapper<>();
            tbClueQueryWrapper2.between("create_time", beginMinTime, endMaxTime);
            tbClueQueryWrapper2.eq("create_by", tbClue.getCreateBy());
            tbClueQueryWrapper2.ge("status", Integer.valueOf(TbClueDTO.StatusType.TOBUSINESS.getValue()));
            Integer fixtureNum = indexMapper.selectCount(tbClueQueryWrapper2);

            // 设置转换率
            if (fixtureNum != null) {
                reportIndexStatisticsData.setRadio(getRadio(num, fixtureNum));
            }


            QueryWrapper<TbClue> tbClueQueryWrapper5 = new QueryWrapper<>();
            tbClueQueryWrapper5.between("create_time", beginMinTime, endMaxTime);
            tbClueQueryWrapper5.eq("create_by", tbClue.getCreateBy());
            List<TbClue> tbClues1 = indexMapper.selectList(tbClueQueryWrapper5);
            if (tbClues1 != null) {
                QueryWrapper<TbAssignRecord> tbClueQueryWrapper3 = new QueryWrapper<>();
                tbClueQueryWrapper3.eq("assign_id", tbClues1.get(0).getId());
                tbClueQueryWrapper3.eq("latest", 1);
                TbAssignRecord tbAssignRecord = tbAssignRecordMapper.selectOne(tbClueQueryWrapper3);
                SysDept sysDept = new SysDept();

                if (tbAssignRecord != null && tbAssignRecord.getDeptId() != null) {
                    QueryWrapper<SysDept> tbClueQueryWrapper4 = new QueryWrapper<>();
                    tbClueQueryWrapper4.eq("dept_id", tbAssignRecord.getDeptId());
                    sysDept = deptMapper.selectOne(tbClueQueryWrapper4);
                }
                if (sysDept != null) {
                    reportIndexStatisticsData.setDeptName(sysDept.getDeptName());


                    reportIndexStatisticsDataList.add(reportIndexStatisticsData);
                }
                // 设置部门名

            }


        }


        return reportIndexStatisticsDataList;
    }
}
